import {PageContainer} from "@ant-design/pro-layout";
import {Button, message, Space, Tree, Upload} from "antd";

import type {Dispatch} from 'umi';
import {connect} from 'umi';
import type {FC} from "react";
import {memo, useEffect, useMemo,} from "react";

import type {DictModelState} from "@/pages/Dict/models/dict.model";
import {DictEffectKeys, dictModelName} from "@/pages/Dict/models/dict.model";
import type {EventDataNode} from "rc-tree/lib/interface";



interface MapToProps {
  loading: {
    global: boolean
  };
  dictModel: DictModelState;
  dispatch: Dispatch
}

const Dict: FC<MapToProps> = memo((props) => {
  const {dispatch, dictModel, loading} = props
  useEffect(() => {
    dispatch({
      type: `${dictModelName}/${DictEffectKeys.Query}`,
      payload: 0
    })
  }, [])


  const onLoadData = useMemo(() => {
    return (treeNode: EventDataNode) => {
      return new Promise<void>((resolve) => {
        dispatch({
          type: `${dictModelName}/${DictEffectKeys.AppendChild}`,
          payload: `${treeNode.key}`
        }).then(() => {
          resolve()
        })
      })
    }
  }, [dispatch])


  const exportData = useMemo(()=>{
    return ()=>{
      window.open(`${REACT_APP_BASE_URL}/cmn/dict/exportData`)
    }
  },[])

  const uploadProps = useMemo(()=>{
    return {
      name: 'file',
      multiple:false,
      showUploadList:false,
      action: `${REACT_APP_BASE_URL}/cmn/dict/importData`,
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          const {code , message: msg} = info.file.response
          if(code && code === 200 ){
            message.success(`${info.file.name} 上传成功`);
            dispatch({
              type: `${dictModelName}/${DictEffectKeys.Query}`,
              payload: 0
            })
          }else {
            message.error(`${info.file.name} 上传失败: ${msg}`);
          }

        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    }
  },[REACT_APP_BASE_URL,dispatch])

  return <PageContainer>
    <div >
      <Space>
       <Button onClick={()=>exportData()}>
         导出
       </Button>
        <Upload
          {...uploadProps}
        >
          <Button>
            导入
          </Button>
        </Upload>
      </Space>
    </div>
    <Tree
      selectable={false}
      key="id"
      loadData={onLoadData}
      treeData={dictModel.dictTreeData}>
    </Tree>

  </PageContainer>
})


export default connect(({loading, dictModel}: MapToProps) => {
  return {
    loading,
    dictModel
  }
},)(Dict);




